import { instructAttachmentPreview } from '@/services/api/api-instruct-attachment';
import { deleteInstructRecord, selectRecord } from '@/services/api/api-instruct-record';
import {
  CheckOutlined,
  CopyOutlined,
  DownloadOutlined,
  FileImageOutlined,
  PaperClipOutlined,
} from '@ant-design/icons';
import { DrawerForm, ModalForm, ProFormInstance } from '@ant-design/pro-form';
import { WaterMark } from '@ant-design/pro-layout';
import {
  Alert,
  Avatar,
  Button,
  Card,
  Descriptions,
  Divider,
  Image,
  message,
  Space,
  Spin,
  Tag,
  Typography,
  Upload,
  UploadFile,
} from 'antd';
import moment from 'moment';
import { useEffect, useRef, useState } from 'react';
import { history, useAccess, useModel } from 'umi';
import AddReceipt from '../receipt/AddReceipt';
import ListReceipt from '../receipt/ListReceipt';
import ReceiptAssign from '../receipt/ReceiptAssign';
import EditRecord from './EditRecord';
import { ManageRecord } from './ManageRecord';
interface DetailsRecordProps {
  item: InstructRecordData.PageVo;
  onClose: () => void;
  triggerMode: 'card' | 'title';
  instructId: string;
}

const DetailsRecord: React.FC<DetailsRecordProps> = ({
  item,
  onClose,
  triggerMode,
  instructId,
}) => {
  const { initialState } = useModel('@@initialState');

  const ref = useRef<ProFormInstance>();

  const access = useAccess();

  const [record, setRecordState] = useState<InstructRecordData.ResultDetails>();

  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewData, setPreviewData] = useState<{
    id: string;
    name: string;
    mimeType: string;
    url?: string;
  }>();
  const [previewOnlineUrl, setPreviewOnlineUrl] = useState<string>();
  const [previewLoading, setPreviewLoading] = useState(true);
  const [drawerFormVisible, setDrawerFormVisible] = useState(false);
  const [reload, setReloadState] = useState(false);
  const getWindowSize = () => ({
    innerHeight: window.innerHeight,
    innerWidth: window.innerWidth,
  });
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const handleResize = () => {
    setWindowSize(getWindowSize());
  };
  useEffect(() => {
    // 监听
    window.addEventListener('resize', handleResize);
    // 销毁
    return () => window.removeEventListener('resize', handleResize);
  });

  const iframeRef = useRef(null);

  useEffect(() => {
    console.log('======1111====instructId=', instructId);

    if (instructId === item.id) {
      if (instructId !== undefined) {
        setDrawerFormVisible(true);
      }
    }
  }, []);

  const handleLoad = () => {
    console.log('加载完成');
    setPreviewLoading(false);
  };
  useEffect(() => {
    const iframe = iframeRef.current;
    iframe?.addEventListener('load', handleLoad);
    return () => {
      iframe?.removeEventListener('load', handleLoad);
    };
  }, [previewOnlineUrl]);

  const getAssignTypeTag = (assignType: number) => {
    let color;
    let name;

    if (assignType === 1) {
      color = 'green';
      name = '全部';
    } else if (assignType === 2) {
      color = 'blue';
      name = '单位';
    } else if (assignType === 3) {
      color = 'orange';
      name = '组团';
    } else if (assignType === 4) {
      color = 'geekblue';
      name = '联络人';
    } else if (assignType === 5) {
      color = 'purple';
      name = '联络人';
    }

    return (
      <Space>
        <Tag color={color}>{name}</Tag>
      </Space>
    );
  };

  /**
   * 获取 详情
   * @param key
   */
  const getSubmitDetails = async () => {
    try {
      const response = await selectRecord({ id: instructId ? instructId : item.id });
      if (response.code === 0) {
        var tempDivElement = document.createElement('div');
        tempDivElement.innerHTML = response.data?.content;

        const textContent = tempDivElement.textContent || tempDivElement.innerText || '';
        setRecordState({
          ...response.data,
          textContent,
        });
      }
    } catch (error) {}
  };

  return (
    <DrawerForm
      visible={drawerFormVisible}
      key={`drawer_form_detail_record_${item.id}`}
      title={
        <div style={{ float: 'right' }}>
          {/* <span>{record?.name}</span> */}

          <Space>
            {access.宣传指令x配置x管理员 && record?.run === 1 && (
              <EditRecord
                key="edit_role"
                recored={item}
                onRefurbish={() => {
                  // actionRef.current?.reload();
                  getSubmitDetails();
                }}
              />
            )}
            {access.宣传指令x配置x管理员 && (
              <ModalForm
                key={'modal_form_release_state_release'}
                title={<>是否删除指令 : {record?.name}</>}
                trigger={
                  <Button type="primary" danger>
                    删除
                  </Button>
                }
                autoFocusFirstInput
                modalProps={{
                  width: 400,
                  // bodyStyle: { textAlign: 'center' },
                  destroyOnClose: true,
                  onCancel: () => console.log('run'),
                }}
                submitTimeout={2000}
                submitter={{
                  submitButtonProps: {
                    type: 'primary',
                    style: { background: '#FF5500' },
                  },
                }}
                onFinish={async (values) => {
                  const res = await deleteInstructRecord({ id: record?.id });
                  if (res.code === 0) {
                    message.success('删除成功');
                    setDrawerFormVisible(false);
                    onClose();
                  }
                  return true;
                }}
              />
            )}
            {access.宣传指令x配置x指令审批 && record?.examine === 0 && (
              <ManageRecord
                title={record?.name}
                id={record?.id}
                type="botton"
                onRefurbish={() => {
                  getSubmitDetails();
                }}
              />
            )}
          </Space>
        </div>
      }
      trigger={
        triggerMode === 'card' ? (
          <div
            style={{
              paddingLeft: 10,
              paddingRight: 10,
              paddingBottom: 10,
            }}
          >
            <Card
              bordered={false}
              hoverable
              style={{
                background: 'linear-gradient(#F5FBFF,#fff, #fff)',
              }}
              // actions={recordActions}
            >
              <Card.Meta
                avatar={
                  <Avatar
                    style={{
                      marginTop: '2px',
                    }}
                    size={'large'}
                    src={item.createdOrganizationAvatar}
                  />
                }
                title={
                  <>
                    <div
                      style={{
                        marginTop: 5,
                        marginRight: 18,
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '100%',
                      }}
                    >
                      <span>{item.createdOrganizationName}</span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      >
                        {access.宣传指令x配置x管理员 && (
                          <Tag
                            color={
                              item?.examine === 0
                                ? '#2db7f5'
                                : item?.examine === 2
                                ? '#f50'
                                : '#87D068'
                            }
                          >
                            {item?.examine === 0 ? '待审批' : item?.examine === 2 ? '退回' : '通过'}
                          </Tag>
                        )}
                        {access.宣传指令x配置x管理员 && (
                          <>
                            {/* <span
                              style={{
                                color: '#1B1B32',
                                fontSize: '13px',
                              }}
                            >
                              要求：
                            </span> */}
                            <Tag color={item?.completeType === 1 ? 'success' : 'error'}>
                              {item?.completeType === 1 ? '无需回执' : '需要回执'}
                            </Tag>
                          </>
                        )}

                        {!access.宣传指令x配置x管理员 && (
                          <>
                            {item.isView === 0 ? (
                              <Tag color={'#F9CF59'} key="recordExamineType">
                                未阅读
                              </Tag>
                            ) : (
                              <Space>
                                {item.isComplete === 1 ? (
                                  <Tag color={'success'}>{'已完成'}</Tag>
                                ) : (
                                  <Tag color={item?.completeType === 1 ? 'success' : 'error'}>
                                    {item?.completeType === 1 ? '无需回执' : '需要回执'}
                                  </Tag>
                                )}
                              </Space>
                            )}
                          </>
                        )}
                      </span>
                    </div>
                    <div
                      style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '90vw',
                        marginTop: '5px',
                      }}
                    >
                      <div>
                        <div
                          style={{
                            float: 'left',
                          }}
                        >
                          {/* {access.宣传指令x配置x管理员 && item.run !== 4 && (
                            <Tag
                              color={
                                item.run === 1
                                  ? 'green'
                                  : item.run === 2
                                    ? 'error'
                                    : item.run === 3
                                      ? 'warning'
                                      : 'success'
                              }
                            >
                              {item.run === 1
                                ? '进行中'
                                : item.run === 2
                                  ? '已结束 '
                                  : item.run === 3
                                    ? '暂停'
                                    : '已完成'}
                            </Tag>
                          )}

                          {access.宣传指令x配置x接收者 &&
                            (item.isView === 0 ? (
                              <Tag
                                color={
                                  item.run === 1
                                    ? 'green'
                                    : item.run === 2
                                    ? 'error'
                                    : item.run === 3
                                    ? 'warning'
                                    : 'success'
                                }
                              >
                                {item.run === 1
                                  ? '进行中'
                                  : item.run === 2
                                  ? '已结束 '
                                  : item.run === 3
                                  ? '暂停'
                                  : '已完成'}
                              </Tag>
                            ) : item.isComplete === 1 || item.completeType === 1 ? (
                              <></>
                            ) : (
                              <Tag
                                color={
                                  item.run === 1
                                    ? 'green'
                                    : item.run === 2
                                    ? 'error'
                                    : item.run === 3
                                    ? 'warning'
                                    : 'success'
                                }
                              >
                                {item.run === 1
                                  ? '进行中'
                                  : item.run === 2
                                  ? '已结束 '
                                  : item.run === 3
                                  ? '暂停'
                                  : '已完成'}
                              </Tag>
                            ))}

                          <Tag
                            color={
                              item.grade === 1 ? '#f50' : item.grade === 2 ? '#ffd591' : '#2db7f5'
                            }
                          >
                            {item.grade === 1 ? '重大' : item.grade === 2 ? '重要' : '一般'}
                          </Tag>

                          <Tag color={item.type === 1 ? '#f50' : '#ffd591'}>
                            {item.type === 1 ? '中宣' : '市宣'}
                          </Tag>
                          {/* {access.宣传指令x配置x管理员 ? getAssignTypeTag(item.assignType) : <></>} */}
                          {access.宣传指令x配置x管理员 &&
                          item.isHasView === 1 &&
                          item.isView === 0 ? (
                            <Tag color={'#F9CF59'} key="tag_is_has_view">
                              需要阅读
                            </Tag>
                          ) : (
                            <></>
                          )}
                          {item.isImage === 1 ? <FileImageOutlined /> : <></>}
                          {item.isFile === 1 ? <PaperClipOutlined /> : <></>}
                        </div>
                      </div>
                    </div>
                  </>
                }
                description={
                  <>
                    <Typography.Paragraph ellipsis={true}>
                      {
                        <span
                          style={{
                            color: '#888A8C',
                            fontSize: 15,
                          }}
                        >
                          {item.name}
                        </span>
                      }
                    </Typography.Paragraph>
                    <div
                      style={{
                        marginTop: 5,
                        marginRight: 18,
                        display: 'flex',
                        justifyContent: 'space-between',
                        width: '100%',
                      }}
                    >
                      <span
                        style={{
                          color: item.run === 1 ? '#F47983' : item.run === 2 ? '#888A8C' : 'orange',
                        }}
                      >
                        截止：
                        {item.deadlineTime.slice(0, 11)}
                      </span>
                      <span
                        style={{
                          float: 'right',
                        }}
                      >
                        {moment(item.createdTime).fromNow()}
                      </span>
                    </div>
                  </>
                }
              />
            </Card>
            <div
              style={{
                borderRadius: 12,
                background: '#FFF',
              }}
            ></div>
          </div>
        ) : (
          <Typography.Text ellipsis={true}>
            <a key="a_detail_record">{item.name} </a>
          </Typography.Text>
        )
      }
      autoFocusFirstInput
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: '100%',
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            // ...defaultDoms,
            access.宣传指令x配置x接收者 && (
              <AddReceipt onSave={() => setReloadState(!reload)} recordId={record?.id} />
            ),
          ];
        },
      }}
      onVisibleChange={(visible) => {
        if (visible) {
          getSubmitDetails();
        } else {
          onClose();
        }
        setDrawerFormVisible(visible);
      }}
    >
      <Spin spinning={record ? false : true}>
        <WaterMark content={`宣传指令 - ${initialState?.currentUser?.name}`}>
          <>
            {record && (
              <>
                <Space
                  wrap
                  style={{
                    marginBottom: '16px',
                  }}
                >
                  {/* {record.run !== 4 && (
                    <Tag
                      color={
                        record.run === 1
                          ? 'green'
                          : record.run === 2
                            ? 'error'
                            : record.run === 3
                              ? 'warning'
                              : 'success'
                      }
                    >
                      {record.run === 1
                        ? '进行中'
                        : record.run === 2
                          ? '已结束 '
                          : record.run === 3
                            ? '暂停'
                            : '已完成'}
                    </Tag>
                  )} */}
                  {access.宣传指令x配置x管理员 && (
                    <Tag
                      color={
                        item?.examine === 0 ? '#2db7f5' : item?.examine === 2 ? '#f50' : '#87D068'
                      }
                    >
                      {item?.examine === 0 ? '待审批' : item?.examine === 2 ? '退回' : '通过'}
                    </Tag>
                  )}
                  <Tag
                    color={record.grade === 1 ? '#f50' : record.grade === 2 ? '#ffd591' : '#2db7f5'}
                  >
                    {record.grade === 1 ? '重大' : record.grade === 2 ? '重要' : '一般'}
                  </Tag>

                  <Tag color={record.type === 1 ? 'green' : 'red'}>
                    {record.type === 1 ? '中宣' : '市宣'}
                  </Tag>
                  {access.宣传指令x配置x管理员 && record.isHasView === 1 && record.isView === 0 ? (
                    <Tag color={'#F9CF59'} key="tag_is_has_view">
                      需要阅读
                    </Tag>
                  ) : (
                    <></>
                  )}
                  {/* {!access.宣传指令x配置x管理员 && < Tag color={record.isView === 0 ? '#F9CF59' : '#1AA15F'} key="recordExamineType">
                    {record.isView === 0 ? '未阅读' : '已阅读'}
                  </Tag>}
                  {!access.宣传指令x配置x管理员 && <Tag color={item?.isComplete === 1 ? 'success' : 'warning'}>
                    {item?.isComplete === 1 ? '已完成' : '未完成'}
                  </Tag>} */}
                  {/* <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                    {record?.completeType === 1 ? '不需要回执' : '需要回执'}
                  </Tag> */}
                </Space>
                {!access.宣传指令x配置x管理员 && (
                  <Descriptions>
                    <Descriptions.Item label="操作情况">
                      <Space wrap>
                        <Tag
                          color={record.isView === 0 ? '#F9CF59' : '#1AA15F'}
                          key="recordExamineType"
                        >
                          {record.isView === 0 ? '未阅读' : '已阅读'}
                        </Tag>
                        {record?.isComplete === 1 ? (
                          <Tag color={'success'}>{'已完成'}</Tag>
                        ) : (
                          <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                            {record?.completeType === 1 ? '无需回执' : '需要回执'}
                          </Tag>
                        )}
                      </Space>
                    </Descriptions.Item>
                  </Descriptions>
                )}
                <Descriptions>
                  <Descriptions.Item label="发布时间">{record?.createdTime}</Descriptions.Item>
                </Descriptions>
                <Descriptions>
                  <Descriptions.Item label="发布单位">
                    {record?.createdOrganizationName}
                  </Descriptions.Item>
                  <Descriptions.Item label="发布人">{record?.createdAccountName}</Descriptions.Item>
                  <Descriptions.Item label="联系方式">
                    {record?.createdAccountPhone}
                  </Descriptions.Item>
                </Descriptions>
                {access.宣传指令x配置x管理员 && (
                  <Descriptions>
                    <Descriptions.Item label="焚毁">
                      <Tag
                        color={
                          record?.isDisappear === 1
                            ? record?.isAlreadyDestroyed === 1
                              ? 'red'
                              : 'orange'
                            : 'green'
                        }
                      >
                        {record?.isDisappear === 1
                          ? record?.isAlreadyDestroyed === 1
                            ? '已焚毁'
                            : '进行中'
                          : '不需要'}
                      </Tag>
                    </Descriptions.Item>
                  </Descriptions>
                )}
                {access.宣传指令x配置x管理员 ? (
                  <Descriptions>
                    {/* <Descriptions.Item label="推送范围">
                      {getAssignTypeTag(record.assignType)}
                    </Descriptions.Item> */}
                    <Descriptions.Item label="指令要求">
                      <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
                        {record?.completeType === 1 ? '无需回执' : '需要回执'}
                      </Tag>
                    </Descriptions.Item>
                    <Descriptions.Item>
                      <ReceiptAssign
                        id={record.id}
                        receipt={'阅读情况：' + record.read}
                        type={'read'}
                        isRun={record.run === 1}
                      />
                    </Descriptions.Item>
                    <Descriptions.Item>
                      {record && record.completeType === 3 && (
                        <ReceiptAssign
                          id={record.id}
                          receipt={'回执情况：' + record.receipt}
                          type={'receipt'}
                          isRun={record.run === 1}
                        />
                      )}
                    </Descriptions.Item>
                  </Descriptions>
                ) : (
                  <></>
                )}
                <Divider />
                {record?.name ? (
                  <Typography.Title
                    copyable={{
                      icon: [
                        <CopyOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copy-icon"
                        />,
                        <CheckOutlined
                          style={{
                            fontSize: '16px',
                          }}
                          key="copied-icon"
                        />,
                      ],
                    }}
                    level={3}
                    style={{ textAlign: 'center' }}
                  >
                    {record?.name}
                  </Typography.Title>
                ) : (
                  <Typography.Title level={3} style={{ textAlign: 'center' }}>
                    暂无标题
                  </Typography.Title>
                )}
                {record?.textContent && (
                  <div
                    style={{
                      marginTop: 5,
                      marginRight: 18,
                      display: 'flex',
                      justifyContent: 'space-between',
                      width: '100%',
                    }}
                  >
                    <span></span>
                    <span
                      style={{
                        float: 'right',
                      }}
                    >
                      <Typography.Paragraph
                        copyable={{
                          icon: [
                            <Tag color="#108ee9" key="copy-icon">
                              复制全文
                            </Tag>,
                            <CheckOutlined
                              style={{
                                fontSize: '16px',
                              }}
                              key="copied-icon"
                            />,
                          ],
                          onCopy: (event) => {
                            console.log('========', event);
                          },
                          text: record?.textContent,
                        }}
                      />
                    </span>
                  </div>
                )}
                <div
                  dangerouslySetInnerHTML={{
                    __html: `${record?.content}`,
                  }}
                />
              </>
            )}
            {record?.attachments && record?.attachments.length > 0 && (
              <>
                <Divider />
                <div
                  style={{
                    textAlign: 'right',
                  }}
                >
                  <Button
                    type="primary"
                    key="import"
                    size="small"
                    icon={<DownloadOutlined />}
                    onClick={() => {
                      record?.attachments.forEach(function (item) {
                        window.open(item.content, '_blank');
                      });
                    }}
                  >
                    全部下载
                  </Button>
                </div>

                <Upload
                  listType="picture"
                  multiple
                  fileList={record?.attachments.map((item) => {
                    return {
                      uid: item.id,
                      name: (
                        <Typography.Text style={{ maxWidth: '40vw' }} ellipsis>
                          {item.name}
                        </Typography.Text>
                      ),
                      url: item.content,
                      mimeType: item.mimeType,
                      status: 'done',
                    };
                  })}
                  showUploadList={{
                    downloadIcon: (
                      <div style={{ marginLeft: '-60px', padding: '17px 0', marginTop: '-15px' }}>
                        <DownloadOutlined
                          style={{
                            marginRight: '10px',
                          }}
                        />
                        点击下载
                      </div>
                    ),
                    showRemoveIcon: false,
                    showDownloadIcon: true,
                  }}
                  onPreview={async (file: UploadFile) => {
                    setPreviewData({
                      id: file.uid,
                      name: file.name,
                      mimeType: file.mimeType,
                      url: file.url,
                    });
                    setPreviewOpen(true);
                  }}
                />
                <DrawerForm
                  title={previewData?.name}
                  drawerProps={{
                    width: '100%',
                    destroyOnClose: true,
                  }}
                  visible={previewOpen}
                  onVisibleChange={async (visible) => {
                    if (visible) {
                      if (
                        previewData?.mimeType !== null &&
                        previewData?.mimeType?.indexOf('image') > -1
                      ) {
                        //图片预览
                      } else {
                        setPreviewLoading(true);
                        const response = await instructAttachmentPreview({
                          id: previewData?.id,
                        });

                        if (response.code === 0) {
                          setPreviewOnlineUrl(response.data);
                        } else {
                          message.error('暂时无法预览');
                          setPreviewLoading(false);
                        }
                      }
                    } else {
                      setPreviewOpen(false);
                      setPreviewData(undefined);
                      setPreviewOnlineUrl(undefined);
                    }
                  }}
                  submitter={{
                    searchConfig: {
                      submitText: '下载',
                    },
                  }}
                  onFinish={async (values) => {
                    window.open(previewData?.url, '_blank');
                  }}
                >
                  <Alert
                    style={{
                      marginBottom: 20,
                    }}
                    message="部分文件系统可能暂不支持在线预览，建议下载到本地"
                    type="warning"
                    showIcon
                  />
                  {previewData?.mimeType !== null &&
                  previewData?.mimeType?.indexOf('image') > -1 ? (
                    <Image width="100%" src={previewData?.url} />
                  ) : (
                    <Spin spinning={previewLoading}>
                      <iframe
                        ref={iframeRef}
                        src={previewOnlineUrl}
                        height={windowSize.innerHeight - 220}
                        width="100%"
                        frameBorder="0"
                        // scrolling="false"
                        allowFullScreen={true}
                        // scrolling={'no'}
                      />
                    </Spin>
                  )}
                </DrawerForm>
              </>
            )}
            <Divider
              style={{
                marginBottom: -10,
              }}
            />
            {record && record.completeType === 3 && (
              <ListReceipt recordId={record?.id} type={2} reload={reload} />
            )}
          </>
        </WaterMark>
      </Spin>
    </DrawerForm>
  );
};

export default DetailsRecord;
